//
//  XHAppDelegate.m
//  xinhua_sx
//
//  Created by 党阳阳 on 14-7-16.
//  Copyright (c) 2014年 dangyangyang. All rights reserved.
//

#import "XHAppDelegate.h"
#import "XHMainViewController.h"
#import "AFNetworking.h"
#import "NewsDetailViewController.h"
#import "fffffff.h"
#import <shareSDK/ShareSDK.h>

#import "WXApi.h"
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>


#import "NewsDetailViewController.h"
@implementation XHAppDelegate
@synthesize dic;
@synthesize stggg;
@synthesize cllocationmanager = _cllocationmanager;
@synthesize la =_la;
@synthesize lg = _lg;
@synthesize fenxiangcode = _fenxiangcode;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
     _lg = @"";
     _la = @"";
    [self loadLI];
    [ShareSDK registerApp:@"1ead897f5eed"];
   // [ShareSDK connectSinaWeiboWithAppKey:@"568898243"
      //                         appSecret:@"38a4f8204cc784f81f9f0daaf31e02e3"
      //                       redirectUri:@"http://www.sharesdk.cn"];
  
    //添加QQ应用  注册网址  http://open.qq.com/
   // [ShareSDK connectQQWithQZoneAppKey:@"100371282"
     //                qqApiInterfaceCls:[QQApiInterface class]
     //                  tencentOAuthCls:[TencentOAuth class]];
    
    //添加微信应用 注册网址 http://open.weixin.qq.com
  

    //添加新浪微博应用 注册网址 http://open.weibo.com
    [ShareSDK connectSinaWeiboWithAppKey:@"220921333"
                             appSecret:@"70e40f4a43c95f3fe6663da8e4704b15"
                             redirectUri:@"https://api.weibo.com/oauth2/default.html"];
    

    //添加微信应用
    [ShareSDK connectWeChatWithAppId:@"wx73bdf79776dbfaf6" //        //此参数为申请的微信AppID
                           wechatCls:[WXApi class]];
    
    //添加QQ应用
    [ShareSDK connectQQWithQZoneAppKey:@"1103433529"                 //该参数填入申请的QQ AppId
                     qqApiInterfaceCls:[QQApiInterface class]
                       tencentOAuthCls:[TencentOAuth class]];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    dic = [[NSMutableDictionary alloc] init];
    [self loadGr];
    BOOL fitrst = [[NSUserDefaults standardUserDefaults] boolForKey:@"firstStart"];
    if (!fitrst)
    {
        
        butoncl* al = [[butoncl alloc] init];
        [al postString:@"014"fff:@""];
        
    }
    
    XHMainViewController *root = [XHMainViewController shareXMMainViewController];
    
    self.window.rootViewController =root;
    [self.window makeKeyAndVisible];
    
    if (fitrst)
    {
        UIView* backGroundView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        [self.window addSubview:backGroundView];
        backGroundView.backgroundColor = [UIColor whiteColor];
        UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, self.window.frame.size.height-57)];
        imageView.image = [UIImage imageNamed:@"启动页.png"];//复制时替换 启动页 上部分
        [backGroundView addSubview:imageView];
        UIImageView* iamgeView2 = [[UIImageView alloc] initWithFrame:CGRectMake( 0  ,imageView.frame.size.height,320,57)];
        iamgeView2.contentMode = UIViewContentModeScaleToFill;
        imageView.contentMode = UIViewContentModeScaleToFill;
        iamgeView2.image = [UIImage imageNamed:@"start_pic.png"]; //复制时替换 启动页 底部
        [backGroundView addSubview:iamgeView2];
        [UIView animateWithDuration:3.5 animations:^(void){
            backGroundView.alpha = 0.0;
        }completion:^(BOOL ff){
            [backGroundView removeFromSuperview];
        }];
       
    }
   
  
    UIRemoteNotificationType types =(UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeAlert);
    //注册消息推送
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:types];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    if (launchOptions) {
        NSDictionary* pushNotificationKey = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
        if (pushNotificationKey) {
            NSString *message = [[pushNotificationKey objectForKey:@"aps"]objectForKey:@"alert"];
            NSString* newsId = [NSString stringWithFormat:@"%@",[pushNotificationKey objectForKey:@"id"]];
            [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"推送通知"
                                                           message:newsId
                                                          delegate:nil
                                                 cancelButtonTitle:@"知道了"
                                                 otherButtonTitles:nil, nil];
            //[alert show];
            fffffff *newsDetailViewController = [[fffffff alloc] initWithNewsId:newsId];
            [self.window.rootViewController presentViewController:newsDetailViewController animated:YES completion:nil];
            
        }
    }

  
    //fffffff *newsDetailViewController = [[fffffff alloc] initWithNewsId:nil];
   // [self.window.rootViewController presentViewController:newsDetailViewController animated:YES completion:nil];
   
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^void (void) {
        //showNetworkActivityIndicator();
        // [self onCheckVersion1];
        [self loadCHee];
    });
    butoncl* al = [[butoncl alloc] init];
    [al postString:@"024"fff:@""];
    return YES;
}
-(void)loadCHee
{

    NSString* https = [NSString stringWithFormat:@"http://183.203.18.45:7001/jeesite/version/%@.plist",URLEND];
    id json = [NSDictionary dictionaryWithContentsOfURL:[NSURL URLWithString:https]];
    [self performSelectorOnMainThread:@selector(tishi:) withObject:json waitUntilDone:YES];
    
}
-(void)tishi:(id)json
{
    //NSLog(@"sender = %@",sender);
    if (json != nil)
    {
        
        NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
        NSString *currentVersion = [infoDic objectForKey:@"CFBundleVersion"];
        
        NSLog(@"cur = %@",currentVersion);
        if (![json[@"items"][0][@"metadata"][@"bundle-version"] isEqualToString:currentVersion] && [json[@"items"][0][@"metadata"][@"bundle-version"] length]>0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"有新的版本更新，是否前往更新？" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"更新", nil];
            alert.tag = 90002;
            [alert show];
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"此版本为最新版本" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            alert.tag = 90001;
            // [alert show];
        }
        
        NSLog(@"json = %@",json[@"items"][0][@"metadata"][@"bundle-version"]);
    }
    else
    {
        
        NSLog(@"error");
    }
    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    
    int badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
    // NSLog(@"badge = %d",badge);
    application.applicationIconBadgeNumber = 0;
    // NSLog(@"badege clean = %d",application.applicationIconBadgeNumber);
    if(badge > 0)
        
    {
        
        badge = 1;
        
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        
    }
    // 处理推送消息
    NSLog(@"userInfo == %@",userInfo);
    NSString *message = [[userInfo objectForKey:@"aps"]objectForKey:@"alert"];
    NSString* title = [userInfo objectForKey:@"id"];
    stggg = title;
    UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"消息" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    view.tag = 20000;
    [view show];
    
    
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"11");
    if (alertView.tag == 20000)
    {
        NSLog(@"22");
        if (buttonIndex == 1)
        {   NSLog(@"3");
            if ([stggg length] > 0)
            { NSLog(@"4");
                fffffff *newsDetailViewController = [[fffffff alloc] initWithNewsId:stggg];
                //[self.window.rootViewController.navigationController pushViewController:newsDetailViewController animated:YES];
                [self.window.rootViewController presentViewController:newsDetailViewController animated:YES completion:nil];
            }
        }
    }
    else if (alertView.tag == 90002)
    {
                   if (buttonIndex==1) {
                // NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/cn/app/id834207906"];
                //[[UIApplication sharedApplication]openURL:url];
                NSString *u=[NSString stringWithFormat:@"http://www.xhsx.org:7001/jeesite/version/%@.html",URLEND];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:u]];//复制时替换成  发布的地址
                
            }
            
        
    }
    
    stggg = nil;
}
-(void)loadGr
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    NSString* uid = [[NSUserDefaults standardUserDefaults] objectForKey:@"UID"];
    NSString* sting = [NSString stringWithFormat:@"http://183.203.18.45:7001/xinhua/m/update-%@.html",uid];
    [manager GET:sting parameters:nil success:^(AFHTTPRequestOperation*operation, id responseObject) {
        id jsonObject = [NSJSONSerialization JSONObjectWithData:operation.responseData
                                                        options:NSJSONReadingAllowFragments
                                                          error:nil];
        NSLog(@"json = %@",jsonObject);
        dic = jsonObject;
    } failure:^(AFHTTPRequestOperation *operation, NSError*error) {
        NSLog(@"error = %@",error);
    }];
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"DeviceToken: {%@}",deviceToken);
    //这里进行的操作，是将Device Token发送到服务端
    
    NSString* areaCode = COUTURYCODE ;//复制时替换成 县区code
    
    NSString* uid = [[NSUserDefaults standardUserDefaults] objectForKey:@"UID"];
    UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"消息" message:uid delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
    //[view show];

    if (!uid)
    {
        NSLog(@"uid not");
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
        NSString *tokenStr = [deviceToken description];
        UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"消息" message:tokenStr delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
        //[view show];
        if (tokenStr == nil)
        {
            UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"消息" message:@"注册失败" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
            ///[view show];
            return;
        }
        NSString *pushToken = [[[tokenStr
                                 stringByReplacingOccurrencesOfString:@"<" withString:@""]
                                stringByReplacingOccurrencesOfString:@">" withString:@""]
                               stringByReplacingOccurrencesOfString:@" " withString:@""] ;
        NSString* str = [NSString stringWithFormat:@"http://183.203.18.45:7001/xinhua/m/ios/regist"];
        NSLog(@"st = %@",str);
         NSDictionary*d = [NSDictionary dictionaryWithObjectsAndKeys:pushToken,@"deviceId",areaCode,@"code",nil,@"username",nil,@"name",nil,@"password",nil,@"email",@"appPackage",@"appPackage",nil,@"createdate",nil,@"updatedate",nil,@"ownGroup",@"IOS",@"mobileType", nil];
        NSLog(@"dic1 = %@",d);
        [manager POST:str parameters:d success:^(AFHTTPRequestOperation*operation, id responseObject) {
            id jsonObject = [NSJSONSerialization JSONObjectWithData:operation.responseData
                                                            options:NSJSONReadingAllowFragments
                                                              error:nil];
            NSLog(@"json11 = %@",jsonObject);
            UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"t" message:jsonObject[@"message"] delegate:self cancelButtonTitle:@"2" otherButtonTitles:nil];
           // [view show];
        } failure:^(AFHTTPRequestOperation *operation, NSError*error) {
            NSLog(@"error11 = %@",error);
        }];
    }
    else
    {
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
        NSString* sting = [NSString stringWithFormat:@"http://183.203.18.45:7001/xinhua/m/update-%@.html",uid];
        [manager POST:sting parameters:nil success:^(AFHTTPRequestOperation*operation, id responseObject) {
            id jsonObject = [NSJSONSerialization JSONObjectWithData:operation.responseData
                                                            options:NSJSONReadingAllowFragments
                                                              error:nil];
            NSLog(@"json = %@",jsonObject);
            dic = jsonObject;
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
            NSString *tokenStr = [deviceToken description];
            UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"消息" message:tokenStr delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
           // [view show];
            if (tokenStr == nil)
            {
                UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"消息" message:@"注册失败" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
                //[view show];
                return ;
            }
            NSString *pushToken = [[[tokenStr
                                     stringByReplacingOccurrencesOfString:@"<" withString:@""]
                                    stringByReplacingOccurrencesOfString:@">" withString:@""]
                                   stringByReplacingOccurrencesOfString:@" " withString:@""] ;
            NSString* str = [NSString stringWithFormat:@"http://183.203.18.45:7001/xinhua/m/ios/regist"];
            NSLog(@"st = %@",str);
            NSDictionary*d = [NSDictionary dictionaryWithObjectsAndKeys:pushToken,@"deviceId",areaCode,@"code",jsonObject[@"name"],@"username",jsonObject[@"nickName"],@"name",jsonObject[@"password"],@"password",jsonObject[@"auditUser"][@"email"],@"email",@"appPackage",@"appPackage",jsonObject[@"auditUser"][@"createDate"],@"createdate",jsonObject[@"auditUser"][@"updateDate"],@"updatedate",jsonObject[@"groupIdss"],@"ownGroup",@"IOS",@"mobileType", nil];
            NSLog(@"dic1 = %@",d);
            [manager POST:str parameters:d success:^(AFHTTPRequestOperation*operation, id responseObject) {
                id jsonObject = [NSJSONSerialization JSONObjectWithData:operation.responseData
                                                                options:NSJSONReadingAllowFragments
                                                                  error:nil];
                NSLog(@"json11 = %@",jsonObject);
                UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"t" message:jsonObject[@"message"] delegate:self cancelButtonTitle:@"2" otherButtonTitles:nil];
               // [view show];
            } failure:^(AFHTTPRequestOperation *operation, NSError*error) {
                NSString* sting = [[NSString alloc] initWithData:operation.responseData encoding:NSUTF8StringEncoding];
                NSLog(@"sting = %@",sting);
                NSLog(@"error1 = %@",error);
            }];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError*error) {
            NSLog(@"error2 = %@",error);
        }];
    }
    
}
-(void)push:(id)enwid
{
    
}
-(void)loadLI
{
    // 判断定位操作是否被允许
    if([CLLocationManager locationServicesEnabled]) {
        self.cllocationmanager = [[CLLocationManager alloc] init];
        
        self.cllocationmanager.delegate = self;
        NSLog(@"开始低位");
    }
    else {
        NSLog(@"无法定位i"); //提示用户无法进行定位操作
      

    }
    
    // 开始定位
    [_cllocationmanager startUpdatingLocation];
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    NSLog(@"定位成功");
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    [self.cllocationmanager stopUpdatingLocation];
    CLLocation *currentLocation = [locations lastObject];

    CLLocationCoordinate2D coor = currentLocation.coordinate;
    _la = [NSString stringWithFormat:@"%f",coor.latitude];
    _lg = [NSString stringWithFormat:@"%f",coor.longitude];
 
     NSLog(@"laffffffff    rfrrrr = %@ , lg = %@",_la, _lg);
    
   
 
    
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
  NSLog(@"定位失败");
    if (error.code == kCLErrorDenied) {
        NSLog(@"error =%@",error);
        // 提示用户出错原因，可按住Option键点击 KCLErrorDenied的查看更多出错信息，可打印error.code值查找原因所在
    }
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err
{
    UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"消息" message:err.description delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
   // [view show];

     NSLog(@"Push Register Error:%@", err.description);
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
-(void)applicationDidBecomeActive:(UIApplication *)application
{
    application.applicationIconBadgeNumber = 0;
}


- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application  handleOpenURL:(NSURL *)url
{
    return [ShareSDK handleOpenURL:url
                        wxDelegate:self];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return [ShareSDK handleOpenURL:url
                 sourceApplication:sourceApplication
                        annotation:annotation
                        wxDelegate:self];
}
//label 换行
/*
 if([[UIDevice currentDevice].systemVersion floatValue]<7.0){
 CGSize titleS = [title sizeWithFont:[_headerL font]
 constrainedToSize:CGSizeMake(270.0, CGFLOAT_MAX)
 lineBreakMode:NSLineBreakByWordWrapping];
 
 _headerL.frame = CGRectMake(_headerL.frame.origin.x, _headerL.frame.origin.y,
 _headerL.frame.size.width, titleS.height);
 }else{
 CGRect titleR = [title boundingRectWithSize:CGSizeMake(270.0, CGFLOAT_MAX)
 options:NSStringDrawingUsesLineFragmentOrigin
 attributes:nil
 context:nil];
 headerL.frame = CGRectMake(_headerL.frame.origin.x, _headerL.frame.origin.y,
 _headerL.frame.size.width, titleR.size.height);
 }
 */
@end
